'''
都来保意外保险产品组合
'''
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "都来保意外保险产品组合"
    # 生成产品数据
    def genProductInfo(self):

        plan = {
            # 年龄段
            "year":[str(i) for i in range(0,71)],
            #保障天数
            "days":["20y"],
            # 保障人数
            "people_count":["1"],
            #保障金额
            "money":["100000","300000","400000","500000"],
            #交费间隔
            "interval":["10"],
            #交费方式
            "payType":["年交","月交"]
        }
        for v in product(plan["year"],plan["days"],plan["people_count"],plan["money"],plan["interval"],plan["payType"]):
            data = Helper.formatProductInfo( plan,v )
            self.mysql.cursor.execute( domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print( domain[self.name]["insert_sql"].format(**data) )
    #执行爬虫
    def requestJson(self,dt=None,mysql=None):
        params = '''
        appName: 
        appSex: M
        appidType: A
        appidNo: 
        appBirthday: 
        appPhone: 
        appPro: 110000
        appCity: 110100
        appAddress: 
        appEmail: 
        name: 
        sex: M
        idType: A
        idNo: 
        birthday: 1993-02-02
        phone: 
        pro: 110000
        city: 110100
        address: 
        email: 
        source: CUS000000046
        planCode: P000000891
        planAmnt: 100000
        polTerm: 20
        poltermType: Y
        payPeriod: 10
        payIntv: 1
        relation: 0
        validate: 
        '''
        data = Helper.perfectJson( params )
        data["birthday"] = "{0}-01-01".format(str(2020-int(dt["year"])))
        data["payIntv"] = "1" if dt["payType"] == "月交" else "12"
        data["planAmnt"] = dt["money"]
        payload = urlencode(data).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and r.json()["success"]:
            price = Helper.decimalParse( r.json()["msg"] )
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            print( data )
            mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            print('\n产品价格数据更新失败:%d*/'%dt["id"])
            mysql.updateTask( data )